﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services.Description;
using Ornament.Messages;
using Ornament.Web;
using Ornament.Messages.Dao;
using Ornament.MVCWebFrame.Models;

namespace Ornament.MVCWebFrame.Controllers
{
    public class MessagesController : Controller
    {
        public ActionResult Works(int pageSize, int pageIndex, string template, ReadState? readState)
        {
            var infos = GetWorks(pageSize, pageIndex, template, readState);
            return View(infos);
        }

        public ActionResult ListWorks(int pageSize, int pageIndex, string template, ReadState? readState)
        {
            var infos = GetWorks(pageSize, pageIndex, template, readState);
            var result = new List<string>();
            foreach (var info in infos)
            {
                result.Add(info.Show(template));
            }
            return Json(result);
        }
        public ActionResult Logs()
        {
            return View();
        }       

        public ActionResult ReadIt(Guid? id)
        {
            try
            {
                OrnamentContext.Current.MessageManager.SetReadState(ReadState.Read, id.Value,
                                                                    OrnamentContext.Current.CurrentUser);
                return Json(new ReturnResult("成功保存", true));
            }
            catch (Exception ex)
            {
                return Json(new ReturnResult(ex, true), JsonRequestBehavior.AllowGet);
            }
        }

        private static IList<Info> GetWorks(int pageSize, int pageIndex, string template, ReadState? readState)
        {
            InfoSearcher searcher = new InfoSearcher()
            {
                PageSize = pageSize,
                PageIndex = pageIndex,
                ReadState = readState ?? ReadState.UnRead,
                RelivateUser = OrnamentContext.Current.CurrentUser,
                TypeNames = new[] { "WorkList" }
            };

            var dao = OrnamentContext.Current.MessageManager.Factory.InfoDao;
            return dao.Find(searcher);
        }



    }
}
